package com.kingdee.pda.plugins.http.serverinterface.impl;

import android.text.TextUtils;
import android.util.Log;

import com.example.basecommon.utils.ConstantUtil;
import com.example.basecommon.utils.PreferencesUtils;
import com.kingdee.pda.MyApplication;
import com.example.basecommon.utils.LoginUtil;
import com.kingdee.pda.plugins.http.common.KeyConstants;
import com.kingdee.pda.plugins.http.common.OnRequestCallback;
import com.kingdee.pda.plugins.http.serverinterface.ILogin;
import com.kingdee.pda.util.CommonUtil;
import com.kingdee.pda.util.ConstantPreference;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 登录实现
 * Created by zhanlg
 * DATE 2021/5/21
 * TIME 10:49
 */
public class LoginImpl implements ILogin {

    private static final String API_LOGIN = "/api/login.do";
    private static final String API_LOGOUT = "/api/logout.do";
    private static final int LOGIN_TYPE = 2;//暂时写死


    @Override
    public void login(String user, String password, String accountId, final OnRequestCallback<String> callback) {
        String apiUrl = ConstantUtil.getServerUrl() + API_LOGIN;
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , setParamValue(user, password, accountId).toString());

        Request request = new Request.Builder()
                .url(apiUrl)
                .post(requestBody)
                .build();
        OkHttpUtils.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                callback.onFailedCallback(false, CommonUtil.getErrorMsg(e.getMessage(), "请求失败！"));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() == 200) {
                    String result = response.body().string();
                    Log.e(LoginImpl.class.getSimpleName(), result);
                    if (!TextUtils.isEmpty(result) && result.contains(KeyConstants.Response.STATE)) {
                        JSONObject resultJson;
                        try{
                            resultJson = new JSONObject(result);
                            String state = resultJson.optString(KeyConstants.Response.STATE);
                            if ("success".equals(state)) {
                                JSONObject data = resultJson.getJSONObject(KeyConstants.Response.DATA);
                                boolean isSuccess = data.optBoolean(KeyConstants.Response.SUCCESS, false);
                                if (isSuccess) {
                                    String token = data.optString("access_token");
                                    String sessionId = data.optString("KERPSESSIONID");
                                    PreferencesUtils.putString(MyApplication.getInstance().getContext(), ConstantPreference.TOKEN, token);
                                    PreferencesUtils.putString(MyApplication.getInstance().getContext(), ConstantPreference.SESSIONID, token);
                                    callback.onSuccessCallback(token, sessionId);
                                } else {
                                    callback.onFailedCallback(false, CommonUtil.getErrorMsg(
                                                    data.optString(KeyConstants.Response.ERROR_DESC),
                                                    resultJson.optString(KeyConstants.Response.ERROR_MSG)));
                                }
                            } else {
                                callback.onFailedCallback(false,
                                        CommonUtil.getErrorMsg(resultJson.optString(KeyConstants.Response.ERROR_MSG), "请求失败！"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            callback.onFailedCallback(false, CommonUtil.getErrorMsg(response.message(), "数据解析失败！"));
                        }
                    } else {
                        callback.onFailedCallback(true, CommonUtil.getErrorMsg(response.message(), "请求失败！"));
                    }
                } else {
                    callback.onFailedCallback(false, response.message());
                }
            }
        });
    }


    private JSONObject setParamValue(String user, String password, String accountId) {
        JSONObject json = new JSONObject();
        try {
            json.put("user", user);
            json.put("password", password);
            json.put("tenantid", accountId);
            json.put("logintype", String.valueOf(LOGIN_TYPE));//传入int型会请求错误
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }

    @Override
    public void logout(final OnRequestCallback<String> callback) {
        String apiUrl = ConstantUtil.getServerUrl() + API_LOGOUT;
        OkHttpClient okHttpClient = new OkHttpClient();
        HttpUrl.Builder httpBuilder = HttpUrl.parse(apiUrl).newBuilder();
        httpBuilder.addQueryParameter("access_token", LoginUtil.getToken());

        final Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .url(httpBuilder.build())
                .get()
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                callback.onFailedCallback(false, CommonUtil.getErrorMsg(e.getMessage(), "请求失败！"));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() == 200) {
                    String result = response.body().string();
                    Log.e(LoginImpl.class.getSimpleName(), result);
                    if (!TextUtils.isEmpty(result) && result.contains(KeyConstants.Response.STATE)) {
                        JSONObject resultJson;
                        try{
                            resultJson = new JSONObject(result);
                            String state = resultJson.optString(KeyConstants.Response.STATE);
                            if ("success".equals(state)) {
                                JSONObject data = resultJson.getJSONObject(KeyConstants.Response.DATA);
                                boolean isSuccess = data.optBoolean(KeyConstants.Response.SUCCESS, false);
                                if (isSuccess) {
                                    callback.onSuccessCallback("", "");
                                } else {
                                    callback.onFailedCallback(false, CommonUtil.getErrorMsg(
                                            data.optString(KeyConstants.Response.ERROR_DESC),
                                            resultJson.optString(KeyConstants.Response.ERROR_MSG)));
                                }
                            } else {
                                callback.onFailedCallback(false,
                                        CommonUtil.getErrorMsg(resultJson.optString(KeyConstants.Response.ERROR_MSG), "请求失败！"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            callback.onFailedCallback(false, CommonUtil.getErrorMsg(response.message(), "数据解析失败！"));
                        }
                    } else {
                        callback.onFailedCallback(true, CommonUtil.getErrorMsg(response.message(), "请求失败！"));
                    }
                } else {
                    callback.onFailedCallback(false, response.message());
                }
            }
        });
    }
}
